<?php

class mailcontents {
  public $title;
  private $db;
  private $mostrecent=array();
  
  public function __construct($title, $db=NULL) {
    $this->title=$title;
    $this->db=$db;
  }
  
  public function headers() {
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    return ($headers);
  }
  
  public function subject() {
    return $this->title;
  }
  
  public function message() {
    $html = $this->htmlhead();
    $html.= $this->htmlbody();
    return $html;
  }
  
  private function htmlhead() {
    $html ="<html><head><title>".$this->title."</title></head>\n";
    return $html;
  }
  
  private function htmlbody() {
    $html ="<body>\n";
    $html ="<h1>Report from ".date("Y-m-d H:m")."</h1>\n";
    $html.=$this->chap_quotesreception();
    $html.=$this->chap_diskusage();
    $html.="</body>";
    return $html;
  }
  
  private function chap_quotesreception() {
    $html ="<h2>Quotes Reception</h2>\n";
    $logarr= $this->db->query_dailylog(date("Y-m-d"));
    $html.="<pre>\n";
    $filecount=0;
    foreach ($logarr as $entry) {
      if ($entry['action'] == "connect" | $entry['action'] == "disconnect" ) {
        $html.=$entry['action']." at ".$entry['datetime']."\n";
      }
      if ($entry['action'] == "download" & $entry['file'] != "") {
        $filecount++;
        $this->mostRecentFile($entry['file'], $entry['filesize']);
      }
      if ($entry['error']>0) {
        $html.="ERROR : ".$entry['action']." ".$entry['file']." ".$entry['remark']."\n";
      }
    }
    $html.="latest files:\n";
    foreach ($this->mostrecent as $ex=>$date) {
      $html.="  ".$ex." : ".$date['date']." (".$date['size'].")\n";
    }
    $html.="</pre>\n";
    return $html;
  }
  
  private function chap_diskusage() {
    $cmdoutput="";
    exec("df -h | grep /dev/sd", $cmdoutput);
    $html ="<h2>Disk Usage</h2>\n";
    $html.="<pre>".implode("\n", $cmdoutput)."</pre>\n";
    return $html;
  }
  
  // name is like CBOT_20120827.txt
  private function mostRecentFile($name, $size) {
    // first validate if filename is not a split file
    if (strpos($name, "_") && strpos($name, ".")) {
      $exp1 = explode("_", $name);
      $exp2 = explode(".", $exp1[1]);
      $ex=$exp1[0];
      $date=$exp2[0];
      if (array_key_exists($ex, $this->mostrecent)) {
        if ($date > $this->mostrecent[$ex]['date']) {
          $this->mostrecent[$ex]['date']=$date;
          $this->mostrecent[$ex]['size']=$size;          
        }
      } else {
        $this->mostrecent[$ex]['date']=$date;
        $this->mostrecent[$ex]['size']=$size;    
      }
    }
  }
}

?>
